// 实现这个项目的构建任务
const { series, parallel, src, dest, watch } = require('gulp')

const babel = require('gulp-babel')

const uglify = require('gulp-uglify')

// const rename = require('gulp-rename')

const gulpif = require('gulp-if')

const sass = require('gulp-sass')(require('sass'))
const swig = require('gulp-swig')

const imagemin = require('gulp-imagemin')

// const gulpLoadPlugins = require('gulp-load-plugins')
// const plugins = gulpLoadPlugins()

const del = require('del')

const browserSync = require('browser-sync').create()

const useref = require('gulp-useref')

const htmlmin = require('gulp-htmlmin')
// const uglify  = require('gulp-uglify')
const cleanCss = require('gulp-clean-css')

const styles = () => {
  return src('src/assets/styles/*.scss', { base: 'src' }).pipe(sass()).pipe(dest('temp'))
}

const scripts = () => {
  return src('src/assets/scripts/*.js', { base: 'src' }).pipe(babel({ presets: ['@babel/preset-env'] })).pipe(dest('temp'))
}

// const data = {
//   title: 'gulp'
// }

const params = require('./zwq.config.js')

const html = () => {
  return src('src/*.html', { base: 'src' }).pipe(
    swig({
      load_json: true,
      data: params
    })
  ).pipe(htmlmin()).pipe(dest('temp'))
}

const extra = () => {
  return src('public/**', { base: 'public' }).pipe(dest('dist'))
}

const cleanFn = () => {
  return del(['dist', 'temp'])
}

const userefFn = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(useref({ searchPath: ['dist', 'node_modules'] })
      .pipe(gulpif(/\.js$/, uglify()))
      .pipe(gulpif(/\.css$/, cleanCss()))
      .pipe(gulpif(/\.html$/, htmlmin({ collapseWhitespace: true })))
      .pipe(dest('dist')))
}

const image = () => {
  return src('src/assets/images/**', { base: 'src' }).pipe(imagemin()).pipe(dest('dist'))
}
const fonts = () => {
  return src('src/assets/fonts/**', { base: 'src' }).pipe(imagemin()).pipe(dest('dist'))
}

const server = () => {
  watch(['src/assets/styles/**'], styles).on('change', browserSync.reload)
  watch(['src/assets/scripts/**'], scripts).on('change', browserSync.reload)
  watch(['src/*.html'], series(html)).on('change', browserSync.reload)
  watch(['src/assets/fonts/**', 'src/assets/images/**', 'public/**'], browserSync.reload())

  return browserSync.init({
    server: {
      baseDir: ['temp', 'public', 'src']
    },
    port: 8088,
    files: ['dist/**']
    // open: false,
  })
}

// 编译
const compile = parallel(styles, scripts, html)
exports.compile = compile

// 打包
// exports.build = series(cleanFn, compile, image, fonts, extra)
const buildFn = series(cleanFn, parallel(series(compile, userefFn), image, fonts, extra))

const develop = series(cleanFn,  compile, extra, server)

// 将外部使用到的任务暴露出去
exports.clean = cleanFn
exports.develop = develop
exports.build = buildFn
